<?php

namespace app\admin\controller;

//前台首页

use think\Request;

class Banner extends Base
{

    //轮播图
    public function all()
    {
        //查询出轮播列表
        $banners = model('Banner')->order('create_time','desc')->paginate(3);
        //定义模板变量
        $viewData = [
            'banners' => $banners
        ];
        //渲染
        $this->assign($viewData);
        return view();
    }

    //图片添加页面
    public function index(){
        return view();
    }

    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->validate(['size'=>2000000,'ext'=>'jpg,png,gif'])->move( 'upload/');
        if($info){
            $path = '/Tp5/public/upload/'.$info->getSaveName();
            return ['code' => 1,'msg' => '图片已选择','url' => str_replace('\\', '/', $path)];
        }else{
            // 上传失败获取错误信息
            return ['code' => 0,'msg' => $file->getError()];
        }
    }

    public function add(Request $request)
    {
        $data = $request->param();
        $validate = new \app\common\validate\Banner();
        if (!$validate->check($data)){
            return ['code' => 0,'msg' => $validate->getError()];
        }
        //创建模型
        $db = new \app\common\model\Banner();
        //_update接收data
        $result = $db->_update($data);
        if ($result){
            return ['code' => 1,'msg' => '上传成功'];
        }else{
            return ['code' => 0,'msg' => '上传失败'];
        }
    }

    //编辑
    public function edit(Request $request)
    {
        //接收id
        $id = $request->param('id');
        //实例化模型
        $db = new \app\common\model\Banner();
        //查询轮播id
        $bannerInfo = $db->where('id',$id)->find();
        //模板变量
        $viewData = [
            'bannerInfo' => $bannerInfo
        ];
        //渲染
        $this->assign($viewData);
        return view();
    }

    //轮播删除
    public function del()
    {
        //查询出文章id
        $bannerInfo = model('Banner')->find(input('post.id'));
        //将查询结果赋值给变量
        $result = $bannerInfo->delete();
        if ($result){
            $this->success('删除成功','admin/banner/all');
        }else{
            $this->error('删除失败');
        }
    }
}
